package com.itany.shop.service.impl;

import com.itany.shop.dao.UserDao;
import com.itany.shop.entity.User;
import com.itany.shop.exception.RequestParameterErrorException;
import com.itany.shop.exception.UserExistException;
import com.itany.shop.exception.UserNotExistException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;
import com.itany.shop.util.MD5Util;
import com.itany.shop.util.ParameterUtil;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年08月14日14:56
 */
public class UserServiceImpl implements UserService {

    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterErrorException, UserExistException {
        UserDao userDao= (UserDao) ObjectFactory.getObject("userDao");
        if(ParameterUtil.isNull(username) || ParameterUtil.isNull(password)|| ParameterUtil.isNull(phone)|| ParameterUtil.isNull(address)){
            throw new RequestParameterErrorException("请求参数有误");
        }

        // //判断用户名是否已经被注册
        // User queryUser=userDao.selectByUsername(username);
        // //如果查询到对应用户了，则表示该用户已经被注册了
        // if(queryUser!=null){
        //     throw new UserExistException("该用户已经被注册");
        // }

        //如果用户名可用，直接添加用户，密码注意，做了加密操作进行保存的
        User user=new User(username, MD5Util.md5(password),phone,address);

        //调用dao方法执行保存操作
        userDao.insertUser(user);
    }

    @Override
    public User login(String username, String password) throws RequestParameterErrorException, UserNotExistException {
        UserDao userDao= (UserDao) ObjectFactory.getObject("userDao");
        if(ParameterUtil.isNull(username)|| ParameterUtil.isNull(password)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        User user=userDao.selectByUsernameAndPassword(username,MD5Util.md5(password));
        if(null==user){
            throw new UserNotExistException("用户名或者密码错误");
        }
        return user;
    }


}
